//
// Created by Tan Ke on 2024/1/17.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

enum action {
    down = 0,
    up = 1,
};

char* convert(char* s, int numRows)
{
    if (strlen(s) <= numRows) {
        return s;
    }

    if (numRows == 1) {
        return s;
    }

    int col = (strlen(s) * strlen(s)) / numRows;
    if (strlen(s) * strlen(s) % numRows > 0) {
        col += 1;
    }

    char** map = (char**)malloc(sizeof(char*) * numRows);
    for (int i = 0; i < numRows; i ++) {
        char* row = (char*)malloc(sizeof(char) * col);
        memset(row, 0, sizeof(char) * col);
        map[i] = row;
    }

    enum action opt = down;

    int rowIndex = 0;
    int colIndex = 0;

    for (int i = 0; i < strlen(s); i ++) {
        map[rowIndex][colIndex] = s[i];

        if (opt == down && rowIndex + 1 >= numRows) {
            opt = up;
        }
        if (opt == up && rowIndex -1 < 0) {
            opt = down;
        }

        if (opt == down) {
            rowIndex = rowIndex + 1;
        }
        if (opt == up) {
            rowIndex = rowIndex - 1;
            colIndex = colIndex + 1;
        }
    }

#if 0
    for (int i = 0; i < numRows; i ++) {
        for (int j = 0; j < col; j ++) {
            if (map[i][j] == 0) {
                printf("  ");
            } else {
                printf("%c ", map[i][j]);
            }
        }
        printf("\n");
    }
    printf("\n");
#endif

    char* result = (char*)malloc(sizeof(char) * (strlen(s) + 1));
    memset(result, 0, (strlen(s) + 1));
    int index = 0;

    for (int i = 0; i < numRows; i ++) {
        for (int j = 0; j < col; j ++) {
            if (map[i][j] != 0) {
                result[index] = map[i][j];
                index += 1;
            }
        }
    }

    return result;
}

int main(void)
{
    printf("%s\n", convert("PAYPALISHIRINGsfsfa;sljfal;sdfjka;ldfjk;aljaj;lsdfjas;lfja;ldfja;ldfj", 6));

    return 0;
}